﻿using System;
using System.IO;
using System.Windows;
using Castle.Windsor;
using Microsoft.Win32;
using SuppKids.Core.Extensions;
using SuppKids.Core.Reporting;
using SuppKids.Core.Reporting.Data;
using SuppKids.Core.Services;
using SuppKids.Resources;
using SuppKids.ViewModels;

namespace SuppKids
{
	public partial class MainWindow : BaseWindow
	{
		public MainWindow(IWindsorContainer container, LicenseService licenseService)
			: base(container, licenseService)
		{
			AppDomain.CurrentDomain.UnhandledException += this.OnUnhandledException;
			InitializeComponent();
		}

		protected override void OnClosed(EventArgs e)
		{
			Environment.Exit(1);
		}

		private void ButtonMenuRaskladkaClick(object sender, RoutedEventArgs e)
		{
			this.Container.Resolve<MenuRaskladka>().ShowDialog();
		}

		private void ButtonMenuRaskladkaEditorClick(object sender, RoutedEventArgs e)
		{
			this.Container.Resolve<MenuRaskladkaEditor>().ShowDialog();
		}

		private void ButtonSkladClick(object sender, RoutedEventArgs e)
		{
			this.Container.Resolve<Sklad>().ShowDialog();
		}

		private void ButtonDishEditorClick(object sender, RoutedEventArgs e)
		{
			this.Container.Resolve<DatabaseEditor>().ShowDialog();
		}

		private void About_Click(object sender, RoutedEventArgs e)
		{
			new About().ShowDialog();
		}

		private void ButtonAnalysisClick(object sender, RoutedEventArgs e)
		{
			var saveFile = new SaveFileDialog
			{
				FileName = "Итоговый анализ.xlsx",
				DefaultExt = ".xlsx",
				Filter = "Excel files (.xlsx)|*.xlsx"
			};

			if (saveFile.ShowDialog() == true)
			{
				Stream stream = null;
				try
				{
					stream = saveFile.OpenFile();
					var reportGenerator = this.Container.Resolve<ReportGeneratorFactory>().GetReportGenerator(ReportType.NormaPitaniya, ReportFormat.Excel);

					var allProducts = this.Container.Resolve<ProductService>().GetAll();
					var reportData = new NormaPitaniyaReportData(allProducts);
					reportGenerator.GenerateReport(reportData, stream);
				}
				catch (Exception)
				{
					MessageBox.Show(Messages.SaveFileError);
				}
				finally
				{
					if (stream != null)
					{
						stream.Dispose();
					}
				}
			}
		}

		private void ButtonLicenseInfoClick(object sender, RoutedEventArgs e)
		{
			this.Container.Resolve<Activation>().ShowDialog();
		}

		private void ButtonChemicalCompositionClick(object sender, RoutedEventArgs e)
		{
			this.Container.Resolve<ChemicalComposition>().ShowDialog();
		}

		private void ButtonNutritionCharacteristicsClick(object sender, RoutedEventArgs e)
		{
			this.Container.Resolve<NutritionCharacteristics>().ShowDialog();
		}



		private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
		{
			var exception = (Exception)e.ExceptionObject;
			var message = exception.GetDetailedMessage(Environment.NewLine);

			if (this.ShowOnTopMessage(message) == MessageBoxResult.OK)
			{
				var saveFile = new SaveFileDialog
				{
					FileName = "Отчёт об ошибке.txt",
					DefaultExt = ".txt",
					Filter = "Текстовые файлы (.txt)|*.txt"
				};

				if (saveFile.ShowDialog() == true)
				{
					Stream stream = null;
					try
					{
						stream = saveFile.OpenFile();
						using (var writer = new StreamWriter(stream))
						{
							writer.Write(exception);
						}
					}
					catch (Exception)
					{
						MessageBox.Show(Messages.SaveFileError);
					}
					finally
					{
						if (stream != null)
						{
							stream.Dispose();
						}
					}
				}
				Application.Current.Shutdown();
			}
		}

		private MessageBoxResult ShowOnTopMessage(string message)
		{
			return MessageBox.Show(
					message,
					"Необработанная ошибка",
					MessageBoxButton.OK,
					MessageBoxImage.Error,
					MessageBoxResult.OK,
					MessageBoxOptions.DefaultDesktopOnly);
		}
	}
}
